// pages/myPic/myPic.js
import { getAllDrawBoard, changeTitle, getImgId, deleteDrawBoard, changeMember, deleteMember, createDrawBoard } from '../../api/api';
import { linkToDraw, showDialog, getUserInfo } from '../../utils/utils'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    drawBoardDatas: [],
    fromDrawIndex: null,
    curIndex: null,
    isShowMoreMenu: false,
    menuGroup: [
      { text: '查看用户权限', value: 'checkAuth' },
      { text: '删除', type: 'warn', value: 'delete' },
    ],
    isShowAuthList: false,
    isInit: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    // 判断用户是否登录
    getUserInfo(false).then(async userInfo => {
      this.init();
    }).catch(() => {
      linkToHome()
    })
  },
  init: async function () {
    wx.showLoading({
      title: '作品加载中',
    })
    const drawBoardDatas = await getAllDrawBoard()
    this.setData({
      drawBoardDatas,
      isInit: true,
    }, () => {
      wx.hideLoading();
    })
  },
  onShow: async function () {
    // 如果是从 draw 页面返回, 更新
    if (this.data.fromDrawIndex) {
      this.init();
      // 更新图片
      // let that = this;
      // 上传图片有延时
      // setTimeout(async () => {
      //   let { imgId } = await getImgId(that.data.drawBoardDatas[that.data.fromDrawIndex]._id);
      //   that.setData({
      //     [`drawBoardDatas[${that.data.fromDrawIndex}].imgId`]: imgId
      //   })
      // }, 1000);
    }
  },

  /**
   * 修改标题
   */
  changeTitle: async function (e) {
    const newTitle = e.detail.value;
    const { title, _id } = this.data.drawBoardDatas[e.target.id];
    if (newTitle !== title) {
      await changeTitle(_id, newTitle)
    }
  },
  // 跳转到 draw 页面
  linkToDraw: function (e) {
    const index = e.target.id;
    this.setData({
      fromDrawIndex: index
    })
    linkToDraw(this.data.drawBoardDatas[index]._id);
  },
  // 展示更多菜单
  showMoreMenu: function (e) {
    const curIndex = e.currentTarget.dataset.index;
    this.setData({
      isShowMoreMenu: true,
      curIndex,
    })
  },
  // 隐藏更多菜单
  hideMoreMenu: function (e) {
    this.setData({
      isShowMoreMenu: false,
    })
  },
  // 点击更多菜单
  clickMoreMenu: function (e) {
    const eventType = e.detail.value;
    switch (eventType) {
      case 'checkAuth':
        this.checkAuth();
        break;
      case 'delete':
        this.deleteDrawBoard();
        break;
    }
  },
  // 查看用户权限
  checkAuth: function (e) {
    this.hideMoreMenu();
    const curMemberLength = Object.keys(this.data.drawBoardDatas[this.data.curIndex].members).length;
    // 没有其他用户
    if (curMemberLength === 1) {
      showDialog({
        title: '没有其他用户',
        content: '快去邀请好友一起涂鸦吧～'
      })
    } else {
      this.setData({
        isShowAuthList: true
      })
    }
  },
  // 删除画板
  deleteDrawBoard: function (e) {
    const curDrawBoardId = this.data.drawBoardDatas[this.data.curIndex]._id
    this.hideMoreMenu();
    showDialog({
      title: '提示',
      content: '删除行为不可逆, 请确定是否删除！',
      showCancel: true,
      confirmText: '我确定',
      successCb: () => {
        wx.showLoading({
          title: '删除中',
        })
        deleteDrawBoard(curDrawBoardId).then(() => {
          wx.hideLoading()
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          })
          // 重新初始化
          this.init();
        }).catch(() => {
          wx.showToast({
            title: '删除失败',
            icon: 'error',
            duration: 2000
          })
        })
      }
    })
  },
  changeMemberAuth(e) {
    const auth = e.detail.value;
    const curDrawBoardId = this.data.drawBoardDatas[this.data.curIndex]._id;
    const openId = e.target.id;
    changeMember(curDrawBoardId, openId, auth);
  },
  deleteMember(e) {
    const curDrawBoardId = this.data.drawBoardDatas[this.data.curIndex]._id;
    const openId = e.target.id;
    const that = this;
    showDialog({
      title: '提示',
      content: '删除行为不可逆, 请确定是否删除！',
      showCancel: true,
      confirmText: '我确定',
      successCb: () => {
        deleteMember(curDrawBoardId, openId).then(() => {
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          })
          let drawBoardDatas = that.data.drawBoardDatas;
          delete (drawBoardDatas[that.data.curIndex].members[openId]);
          // 如果没有其他用户, 则关闭弹窗
          if (Object.keys(drawBoardDatas[that.data.curIndex].members).length === 1) {
            that.setData({
              isShowAuthList: false,
              drawBoardDatas
            })
          } else {
            that.setData({
              drawBoardDatas
            })
          }
        }).catch((err) => {
          wx.showToast({
            title: '删除失败',
            icon: 'error',
            duration: 2000
          })
        })
      }
    })
  },
  beginDrawBtn: async function (e) {
    getUserInfo().then(
      userInfo => {
        this.createBoard(userInfo)
      }
    )
  },
  createBoard: async function (userInfo) {
    wx.showLoading({
      title: '创建画板中～',
    })
    const { drawBoardId } = await createDrawBoard(userInfo);
    wx.hideLoading();
    linkToDraw(drawBoardId);
  }
})